﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Dungeon_Dive
{
    /// <summary>
    /// This class just holds a helper function for calculating bounding box from Model data.
    /// Code found in the wild.
    /// </summary>
    static class BorrowedTools
    {
        public static Vector3[] tempVecs3 = new Vector3[512]; 
        public static ushort[] tempUshorts = new ushort[512 * 3]; 
 
        public static void CalculateBoundingBox(ModelMesh mm, out BoundingBox bb) 
        { 
            bb = new BoundingBox(); 
            bool first = true; 
            Matrix x = Matrix.Identity; 
            ModelBone mb = mm.ParentBone; 
            while (mb != null) 
            { 
                x = x * mb.Transform; 
                mb = mb.Parent; 
            } 
            foreach (ModelMeshPart mp in mm.MeshParts) 
            { 
                int n = mp.NumVertices; 
                if (n > tempVecs3.Length) 
                  tempVecs3 = new Vector3[n + 128]; 
                int l = mp.PrimitiveCount * 3; 
                if (l > tempUshorts.Length) 
                  tempUshorts = new ushort[l + 128]; 
                if (n == 0 || l == 0) 
                  continue; 
                mm.IndexBuffer.GetData<ushort>(tempUshorts, mp.StartIndex, l); 
                mm.VertexBuffer.GetData<Vector3>(mp.StreamOffset, tempVecs3, mp.BaseVertex, n, mp.VertexStride); 
                if (first) 
                { 
                    bb.Min = Vector3.Transform(tempVecs3[tempUshorts[0]], x); 
                    bb.Max = bb.Min; 
                    first = false; 
                } 
                for (int i = 0; i != l; ++i) 
                { 
                    ushort us = tempUshorts[i]; 
                    Vector3 v = Vector3.Transform(tempVecs3[us], x); 
                    Vector3.Max(ref v, ref bb.Max, out bb.Max); 
                    Vector3.Min(ref v, ref bb.Min, out bb.Min); 
                } 
            } 
        } 
    }
}
